<template>
  <div>
    <el-card>
      <el-alert title="添加商品信息" type="info" show-icon center closable>
      </el-alert>
      <!-- 步骤条 -->
      <el-steps
        :space="300"
        :active="active - 0"
        finish-status="success"
        align-center
      >
        <el-step title="基本信息"> </el-step>
        <el-step title="商品参数"></el-step>
        <el-step title="商品属性"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>
      <!-- tabs区域 -->
      <el-form
        :model="addForm"
        :rules="addRules"
        ref="addFormRef"
        label-width="100px"
        label-position="top"
      >
        <el-tabs
          v-model="active"
          :tab-position="tabPosition"
          :before-leave="beforeTab"
          @tab-click="tabClick"
        >
          <el-tab-pane label="基本信息" name="0">
            <el-form-item label="商品名称" prop="goods_name">
              <el-input v-model="addForm.goods_name"></el-input>
            </el-form-item>
            <el-form-item label="商品价格" prop="goods_price">
              <el-input v-model="addForm.goods_price" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品重量" prop="goods_weight">
              <el-input v-model="addForm.goods_weight" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品数量" prop="goods_number">
              <el-input v-model="addForm.goods_number" type="number"></el-input>
            </el-form-item>
            <el-form-item label="分类" prop="goods_cat">
              <el-cascader
                v-model="addForm.goods_cat"
                :options="cateList"
                :props="cateProps"
                @change="handleChange"
              ></el-cascader>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品参数" name="1">
            <el-form-item
              :label="item.attr_name"
              v-for="item in manyTableData"
              :key="item.attr_id"
            >
              <el-checkbox-group v-model="item.attr_vals">
                <el-checkbox
                  border
                  :label="cb"
                  v-for="(cb, i) in item.attr_vals"
                  :key="i"
                ></el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品属性" name="2">
            <el-form-item
              :label="item.attr_name"
              v-for="item in onlyTableData"
              :key="item.attr_id"
            >
              <el-input v-model="item.attr_vals"></el-input>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品图片" name="3">
            <!-- action api 地址   -->
                <!-- on-preview 预览图片的方法 -->
                <!-- list-type 图片呈现方式--> -->
            <el-upload
              action="http://127.0.0.1:8888/api/private/v1/upload"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              list-type="picture"
              :headers="headerObj"
              :on-success="addimag"
              :on-error="imgErrorInfo"
            >
              <el-button size="small" type="primary">点击上传</el-button>
              <div slot="tip" class="el-upload__tip">
                只能上传jpg/png文件，且不超过500kb
              </div> </el-upload
            ><!--  -->
          </el-tab-pane>
          <el-tab-pane label="商品内容" name="4">
            <!-- 富文本框 -->
            <quill-editor v-model="addForm.goods_introduce"></quill-editor>
            <el-button type="primary" @click="add">添加商品</el-button>
          </el-tab-pane>
        </el-tabs>
      </el-form>
    </el-card>
    <el-dialog :visible.sync="dialogVisible">
  <img width="100%" :src="previewPath" alt="">
</el-dialog>
  </div>
</template>

<script>
/*eslint-disable*/
import _ from 'lodash'
export default {
  data() {
    return {
      // 预览图片地址
      previewPath:'',
      //图片上传的请求头
      headerObj:{Authorization:window.sessionStorage.getItem('token')},
      // 动态参数列表
      manyTableData: [],
      // 静态态参数列表
      onlyTableData: [],
      TorF: true,
      cateProps: {
        expandTrigger: "hover",
        label: "cat_name",
        children: "children",
        value: "cat_id",
      },
      // 商品类型列表
      cateList: [],
      active: "0",
      tabPosition: "left",
      // 表单数据
      addForm: {
        pics:[],
        goods_name: "",
        goods_price: "",
        goods_weight: "",
        goods_number: "",
        goods_cat: [],
        goods_introduce:'',
        attrs:[]
      },
      dialogVisible:false,
      // 表单验证规则
      addRules: {
        goods_name: [
          { required: true, message: "请输入数据", trigger: "blur" },
        ],
        goods_cat: [{ required: true, message: "请选择分类", trigger: "blur" }],
        goods_price: [
          { required: true, message: "请选择分类2", trigger: "blur" },
        ],
        goods_number: [
          { required: true, message: "请选择分类3", trigger: "blur" },
        ],
        goods_weight: [
          { required: true, message: "请选择分类4", trigger: "blur" },
        ],
      },
    };
  },
  created() {
    this.getCateList();
  },
  methods: {
    async getCateList() {
      const { data: res } = await this.$http.get("/categories");
      if (res.meta.status !== 200) {
        return this.$message.error("获取分类数据失败");
      }
      this.cateList = res.data;
    },
    // 级联选择器发生变化时触发
    handleChange() {
      if (this.addForm.goods_cat.length !== 3) {
        this.addForm.goods_cat = [];
      }
      console.log(this.addForm.goods_cat);
    },
    // 点击切换页面时触发 activName要进去的页面名称 oldActivName即将退出的页面名称
    beforeTab(activName, oldActivName) {
      this.$refs.addFormRef.validate((v) => {
        if (!v) {
          this.TorF = false;
        } else {
          this.TorF = true;
        }
      });
      return this.TorF;
    },
    async tabClick() {
      if (this.active === "1") {
        const { data: res } = await this.$http.get(
          `categories/${this.cateId}/attributes`,
          { params: { sel: "many" } }
        );
        if (res.meta.status !== 200) {
          return this.$message.error("未知错误");
        }
        res.data.forEach((element) => {
          element.attr_vals =
            element.attr_vals.length === 0 ? [] : element.attr_vals.split(" ");
        });
        this.manyTableData = res.data;
      } else if (this.active === "2") {
        const { data: res } = await this.$http.get(
          `categories/${this.cateId}/attributes`,
          { params: { sel: "only" } }
        );
        if (res.meta.status !== 200) {
          return this.$message.error("未知错误");
        }
        this.onlyTableData = res.data;
        console.log(res.data);
      }
    },
    // on-preview 预览图片的方法-->
    handlePreview(file){
      console.log(file);
      this.previewPath=file.response.data.url
      console.log(this.previewPath);
      this.dialogVisible=true

    },
    // 去除图片的方法
    handleRemove(file){ 
      // 获得将要删除的图片临时路径
      const filePath=file.response.data.tmp_path
      // 调用js数组函数splice 将数据从pics数组中删除
      const i = this.addForm.pics.findIndex(x =>{
        x.pic === filePath
      })
      this.addForm.pics.splice(i,1)
    },
    // 监听图片上传成功事件
    addimag(response){
      const picInfo = {pic:response.data.tmp_path}
      this.addForm.pics.push(picInfo)
    },
    async add(){ 
      // lodash cloneDeep(obj) 深拷贝
     const from = _.cloneDeep(this.addForm)
     from.goods_cat=from.goods_cat.join(',')
     this.manyTableData.forEach(i =>{
       const newInfo={attr_id:i.attr_id,attr_value:i.attr_vals.join(',')}
       this.addForm.attrs.push(newInfo)
     })
      this.onlyTableData.forEach(i =>{
       const newInfo={attr_id:i.attr_id,attr_value:i.attr_vals}
       this.addForm.attrs.push(newInfo)
     })
     from.attrs = this.addForm.attrs

    const {data:res} = await this.$http.post('/goods',from)
     if(res.meta.status !== 201){
       return this.$message.error('提交失败')

     }
     this.$message.success('提交成功')
     this.$router.push('/goods')



},
imgErrorInfo(){}
  },
  // 计算方法
  computed: {
    cateId() {
      if (this.addForm.goods_cat.length === 3) {
        return this.addForm.goods_cat[2];
      }
      return null;
    },
  },
};
</script>

<style lang="less" scoped>
.el-checkbox {
  margin-right: 10px;
}
.el-button{
  margin: 20px;
}
</style>
